#include "snapshot.h"
#include <QPainter>
#include <QAction>
#include <QMenu>
#include <QCursor>
#include <QColorDialog>
#include <QFileDialog>
#include "log.h"
#include <QDir>
#include <QDateTime>
#include "appcontroller.h"
#include "globalmgr.h"
#include <QMessageBox>
#include <ctime>


SnapShot::SnapShot(QWidget *parent) : QWidget(parent)
{

}

SnapShot::SnapShot(QPixmap &pix, QWidget *parent)
    :showPix(pix)
    ,QWidget(parent)
    ,bMouseMove(false)
    ,contentMenu(nullptr)
    ,borderColor(QColor(255,255,0))
    ,bMouseInWight(false)
{
    srand(time(0));

    this->setGeometry(0,0,showPix.width(),showPix.height());
    setWindowOpacity(1);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    borderColor = RandBorderColor();
    scaleSize = showPix.size();
    auto miniSize = GlobalMgr::GetInstance()->GetMiniSize();
    scaleFactorW = showPix.size().width() / miniSize.width() ;
    scaleFactorH = showPix.size().height() / miniSize.height() ;

    createActionMenu();
}

SnapShot::~SnapShot()
{
    if(contentMenu){
        delete contentMenu;
        contentMenu = nullptr;
    }
}

void SnapShot::ShowMenu()
{
    if(contentMenu){
        QCursor cur=this->cursor();
        contentMenu->exec(cur.pos()); //关联到光标
    }
}

void SnapShot::CloseWidget()
{
    AppController::GetInstance()->RemoveSnapShot(this);
    deleteLater();
}

void SnapShot::SavePix()
{
    QString fileName;
    auto mgr = GlobalMgr::GetInstance();
    fileName = mgr->GetQuickSavePath();
    fileName +="/";

    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("yyyy-MM-dd[hh-mm-ss]");
    Log<<current_date;
    fileName +=current_date;
    fileName +=mgr->GetSaveTypeToString();
    if(!(showPix.save(fileName))){
        QMessageBox::critical(NULL
                              , tr("保存失败")
                              , tr("请检查快速保存路径是否正确!!!")
                              , QMessageBox::Ok, QMessageBox::Ok);
        return;
    }
}

void SnapShot::SetBorderColor()
{
    borderColor= QColorDialog::getColor(Qt::white, this);
}

void SnapShot::SaveAsPix()
{
    QString fileName = QFileDialog::getSaveFileName(this,
                                                    tr("保存图片"),
                                                    "",
                                                    tr("Files (*.png)"));

    if (!fileName.isNull()){
        Log<<fileName;

        if(!(showPix.save(fileName))){
            QMessageBox::critical(NULL
                                  , tr("保存失败")
                                  , tr("请检查保存路径是否正确!!!")
                                  , QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
    }
}

void SnapShot::showEvent(QShowEvent *event)
{

}

void SnapShot::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setPen(borderColor);
    QPoint pot(0,0);
    painter.drawPixmap(pot.x(), pot.y(),scaleSize.width(),scaleSize.height(), showPix);
    painter.drawRect(pot.x(),pot.y(),scaleSize.width()-1,scaleSize.height()-1);
}

void SnapShot::mousePressEvent(QMouseEvent *event)
{
    bMouseMove=true;
    mousePressPos = event->globalPos() - this->pos();
}

void SnapShot::mouseMoveEvent(QMouseEvent *event)
{
    if(bMouseMove){
        move(event->globalPos() - mousePressPos);
    }
}

void SnapShot::mouseReleaseEvent(QMouseEvent *event)
{
    bMouseMove=false;
}

void SnapShot::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(showPix.size() == scaleSize){    // 还原
        scaleSize = GlobalMgr::GetInstance()->GetMiniSize();
        redress(event->pos());
    }
    else{    //最小化
        scaleSize = showPix.size();
    }

    repaint();
}

void SnapShot::contextMenuEvent(QContextMenuEvent *)
{
    ShowMenu();
}

void SnapShot::keyPressEvent(QKeyEvent *event)
{
    QPoint curPos = this->pos();
    switch(event->key())
    {
    case Qt::Key_Up:
        curPos.setY(curPos.y()-1);
        break;
    case Qt::Key_Down:
        curPos.setY(curPos.y()+1);
        break;
    case Qt::Key_Left:
        curPos.setX(curPos.x()-1);
        break;
    case Qt::Key_Right:
        curPos.setX(curPos.x()+1);
        break;
    case Qt::Key_Escape:
        CloseWidget();
        break;
    }

    this->move(curPos);
}

void SnapShot::enterEvent(QEvent *event)
{
    //Log<<"mouse enter event!!!";
    bMouseInWight = true;
}

void SnapShot::leaveEvent(QEvent *event)
{
    //Log<<"mouse leave event!!!";
    bMouseInWight =false;
}

void SnapShot::wheelEvent(QWheelEvent *event)
{
    if(bMouseInWight){
        //Log<<" whell delta = " <<event->delta();
        if(event->delta() > 0){ // 放大
            scaleSize.setWidth(scaleSize.width() + scaleFactorW);
            scaleSize.setHeight(scaleSize.height() + scaleFactorH);

        }else{ //缩小
            scaleSize.setWidth(scaleSize.width() - scaleFactorW);
            scaleSize.setHeight(scaleSize.height() - scaleFactorH);
        }

        if(showPix.size().width() < scaleSize.width()){
            scaleSize = showPix.size();
        }
        if(GlobalMgr::GetInstance()->GetMiniSize().width() > scaleSize.width()){
            scaleSize = GlobalMgr::GetInstance()->GetMiniSize();
        }
        repaint();
    }
}

void SnapShot::createActionMenu()
{
    auto closeAct = new QAction(tr("丢弃"), this);
    closeAct->setIcon(QIcon(":/icon/res/drop_icon.png"));
    connect(closeAct, SIGNAL(triggered()), this, SLOT(CloseWidget()));
    auto saveAct = new QAction(tr("快速保存"), this);
    saveAct->setIcon(QIcon(":/icon/res/quicksave_icon.png"));
    connect(saveAct, SIGNAL(triggered()), this, SLOT(SavePix()));
    auto colorSetAct = new QAction(tr("边框颜色"), this);
    colorSetAct->setIcon(QIcon(":/icon/res/border_icon.png"));
    connect(colorSetAct, SIGNAL(triggered()), this, SLOT(SetBorderColor()));
    auto saveAsAct = new QAction(tr("另存为"),this);
    saveAsAct->setIcon(QIcon(":/icon/res/saveas_icon.png"));
    connect(saveAsAct , SIGNAL(triggered()),this,SLOT(SaveAsPix()));

    contentMenu=new QMenu(this);
    contentMenu->addAction(colorSetAct);
    contentMenu->addSeparator();
    contentMenu->addAction(saveAct);
    contentMenu->addAction(saveAsAct);
    contentMenu->addSeparator();
    contentMenu->addAction(closeAct);

}

QPoint SnapShot::redress(QPoint pos)
{
    QPoint pot = pos;
    QSize minSize= GlobalMgr::GetInstance()->GetMiniSize();
    if(showPix.width() - pos.x() < minSize.width())
        pot.setX(showPix.width() - minSize.width());
    if(showPix.height() - pos.y() < minSize.height())
        pot.setY(showPix.height() - minSize.height());
    return pot;
}

QColor SnapShot::RandBorderColor()
{
    static QColor colVec[] = {
        QColor(255,0,0),
        QColor(0,255,0),
        QColor(0,0,255),
        QColor(255,255,0),
        QColor(0,255,255),
        QColor(255,0,255),
        QColor(21,249,198),
        QColor(251,157,34),
    };

    static int idx=0;
    idx++;

    int arrayNum = sizeof(colVec) / sizeof(colVec[0]);
    int n = idx % arrayNum;
    Log<<"n = " <<n<<"  arrayNum = "<<arrayNum;

    return colVec[n];
}
